package com.boruan.shengtangfeng.core.service.impl;

import com.boruan.shengtangfeng.core.dao.*;
import com.boruan.shengtangfeng.core.dto.GroupDataDto;
import com.boruan.shengtangfeng.core.entity.*;
import com.boruan.shengtangfeng.core.service.IChitchatService;
import com.boruan.shengtangfeng.core.service.IMessageService;
import com.boruan.shengtangfeng.core.tencentEntity.CreateGroupReturn;
import com.boruan.shengtangfeng.core.utils.*;
import com.boruan.shengtangfeng.core.vo.*;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: guojiang
 * @Description:
 * @date:2021年3月31日 下午14:08
 */
@Service
@Transactional(readOnly = false)
@SuppressWarnings("all")
public class ChitchatServiceImpl implements IChitchatService {

    @Autowired
    private IUserDao userDao;
    @Autowired
    private IUserFriendAndBlacklistDao userFriendAndBlacklistDao;
    @Autowired
    private IGroupMembersDao groupMembersDao;
    @Autowired
    private IGroupChatDao groupChatDao;
    @Autowired
    private IApplyForDao applyForDao;
    @Autowired
    private ChineseInital chineseInital;
    @Autowired
    private IKickOutDao kickOutDao;
    @Autowired
    private IInviteAddGroupDao inviteAddGroupDao;
    @Autowired
    private IClassAndDao classAndDao;
    @Autowired
    private IClassMembersDao classMembersDao;
    @Autowired
    private TencentUtil tencentUtil;
    @Autowired
    private IMessageService messageService;

    /**
     * 获取好友列表
     *
     * @param userId
     * @return
     */
    @Override
    public GlobalReponse<UserRelevanceVo> getList(Long userId, Integer type, String keyword) {
//        UserFriendAndBlacklist userFriendAndBlacklist = new UserFriendAndBlacklist();
//        userFriendAndBlacklist.setUserId(userId);
//        userFriendAndBlacklist.setType(0);
//        userFriendAndBlacklist.setType(type);
//        userFriendAndBlacklist.setIsDeleted(false);
        if (keyword != null && keyword.equals("")) {
            keyword = null;
        }
        List<UserFriendAndBlacklist> template = userFriendAndBlacklistDao.getList(userId, type, keyword);
        if (template.isEmpty()) {
            return GlobalReponse.success("暂无数据");
        }
        if (type == 0) {
            List<UserRelevanceVo> vos = new ArrayList<>();
            for (UserFriendAndBlacklist friend : template) {
                User user = userDao.unique(friend.getRelevanceId());
                UserRelevanceVo vo = new UserRelevanceVo();
                vo.setRelevanceId(friend.getRelevanceId());
                vo.setRelevanceImage(user.getHeadImage());
                vo.setRelevanceNickName(user.getName());
                vos.add(vo);
            }
            Map<String, List<UserRelevanceVo>> res = vos.stream()
                    .collect(Collectors.groupingBy(firstLetter -> {
                        return chineseInital.getFirstLetter(firstLetter.getRelevanceNickName()).toUpperCase();
                    }, TreeMap::new, Collectors.toList()));

            ArrayList maps = new ArrayList<>();
            for (Map.Entry<String, List<UserRelevanceVo>> entry : res.entrySet()) {
                Map map = new IdentityHashMap<>();
                map.put("letter", entry.getKey());
                map.put("list", entry.getValue());
                maps.add(map);
            }
            return GlobalReponse.success(maps);
        }
        if (type == 1) {
            List<UserRelevanceVo> vos = new ArrayList<>();
            for (UserFriendAndBlacklist blacklist : template) {
                GroupChat chat = groupChatDao.unique(blacklist.getRelevanceId());
                UserRelevanceVo vo = new UserRelevanceVo();
                vo.setRelevanceId(chat.getId());
                if (chat.getHead() != null && !chat.getHead().equals("")) {
                    vo.setRelevanceImage(chat.getHead());
                } else {
                    String head = "";
                    List<GroupMembers> groupMembers = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, chat.getId()).andEq(GroupMembers::getIsDeleted, 0).desc(GroupMembers::getType).limit(1, 9).select();
                    for (GroupMembers groupMember : groupMembers) {
                        User user = userDao.unique(groupMember.getUserId());
                        if (user.getHeadImage() != null) {
                            if (head.equals("")) {
                                head = user.getHeadImage();
                            } else {
                                head = head + "," + user.getHeadImage();
                            }
                        }
                    }
                    vo.setRelevanceImage(head);
                }
                vo.setRelevanceNickName(chat.getName());
                vos.add(vo);
            }
            return GlobalReponse.success(vos);
        }

        if (type == 2) {
            List<UserRelevanceVo> vos = new ArrayList<>();
            for (UserFriendAndBlacklist blacklist : template) {
                User user = userDao.unique(blacklist.getRelevanceId());
                UserRelevanceVo vo = new UserRelevanceVo();
                vo.setRelevanceId(user.getId());
                vo.setRelevanceImage(user.getHeadImage());
                vo.setRelevanceNickName(user.getName());
                vos.add(vo);
            }
            return GlobalReponse.success(vos);
        }

        return GlobalReponse.fail("查询失败");
    }

    /**
     * 加入或移出黑名单 type 0移出 1加入
     *
     * @param userId
     * @param friendId
     * @param type
     * @return
     */
    @Override
    public GlobalReponse addOrRemoveBlack(Long userId, Long friendId, Integer type) {
        if (type == 1) {
            Boolean flag = tencentUtil.blackListAdd(userId, friendId);
            if (!flag) {
                return GlobalReponse.fail("加入黑名单失败");
            }
            UserFriendAndBlacklist single = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, userId).andEq(UserFriendAndBlacklist::getRelevanceId, friendId).andEq(UserFriendAndBlacklist::getType, 2).andEq(UserFriendAndBlacklist::getIsDeleted, false).single();
            if (single != null) {
                return GlobalReponse.success("已加入黑名单");
            }
            UserFriendAndBlacklist blacklist = new UserFriendAndBlacklist();
            blacklist.setUserId(userId);
            blacklist.setRelevanceId(friendId);
            blacklist.setType(0);
            blacklist.setIsDeleted(false);
            UserFriendAndBlacklist templateOne = userFriendAndBlacklistDao.templateOne(blacklist);
            if (templateOne != null) {
                templateOne.setType(2);
                templateOne.setUpdateBy(userId.toString());
                templateOne.setUpdateTime(new Date());
                userFriendAndBlacklistDao.updateTemplateById(templateOne);
            } else {
                UserFriendAndBlacklist balck = new UserFriendAndBlacklist();
                balck.setUserId(userId);
                balck.setRelevanceId(friendId);
                balck.setType(2);
                balck.setIsDeleted(false);
                balck.setCreateTime(new Date());
                balck.setCreateBy(userId.toString());
                userFriendAndBlacklistDao.insertTemplate(balck);
            }
            UserFriendAndBlacklist blacklist1 = new UserFriendAndBlacklist();
            blacklist1.setUserId(friendId);
            blacklist1.setRelevanceId(userId);
            blacklist1.setType(0);
            blacklist1.setIsDeleted(false);
            UserFriendAndBlacklist templateOne1 = userFriendAndBlacklistDao.templateOne(blacklist1);
            if (templateOne1 != null) {
                templateOne1.setIsDeleted(true);
                templateOne1.setUpdateBy(userId.toString());
                templateOne1.setUpdateTime(new Date());
                userFriendAndBlacklistDao.updateTemplateById(templateOne1);
            }
            return GlobalReponse.success("加入黑名单成功");
        }
        if (type == 0) {
            Boolean flag = tencentUtil.blackListDelete(userId, friendId);
            if (!flag) {
                return GlobalReponse.fail("移出黑名单失败");
            }
            UserFriendAndBlacklist blacklist = new UserFriendAndBlacklist();
            blacklist.setUserId(userId);
            blacklist.setRelevanceId(friendId);
            blacklist.setType(2);
            blacklist.setIsDeleted(false);
            UserFriendAndBlacklist templateOne = userFriendAndBlacklistDao.templateOne(blacklist);
            if (templateOne != null) {
                templateOne.setIsDeleted(true);
                templateOne.setUpdateBy(userId.toString());
                templateOne.setUpdateTime(new Date());
                userFriendAndBlacklistDao.updateTemplateById(templateOne);
            }
            return GlobalReponse.success("移出黑名单成功");
        }
        return GlobalReponse.fail("操作失败");
    }

    /**
     * 删除好友
     *
     * @param userId
     * @param friendId
     * @return
     */
    @Override
    public GlobalReponse deletedFriend(Long userId, Long friendId) {
        UserFriendAndBlacklist single = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, userId).andEq(UserFriendAndBlacklist::getRelevanceId, friendId).andEq(UserFriendAndBlacklist::getIsDeleted, false).single();
        UserFriendAndBlacklist single1 = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, friendId).andEq(UserFriendAndBlacklist::getRelevanceId, userId).andEq(UserFriendAndBlacklist::getIsDeleted, false).single();
        single.setIsDeleted(true);
        userFriendAndBlacklistDao.updateTemplateById(single);
        if (single1 != null) {
            single1.setIsDeleted(true);
            userFriendAndBlacklistDao.updateTemplateById(single1);
        }
        Boolean flag = tencentUtil.friendDelete(single.getUserId(), single.getRelevanceId());
        if (flag) {
            return GlobalReponse.success("删除成功");
        }
        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        return GlobalReponse.fail("删除失败");

    }

    /**
     * 根据id或名称搜索好友或群聊 type 0好友 1群聊
     *
     * @param parameter
     * @param type
     * @return
     */
    @Override
    public GlobalReponse searchFriendOrGroup(Long userId, String parameter, Integer type) {
        if (type == 0) {
            List<UserFriendAndBlacklist> select = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, userId).andEq(UserFriendAndBlacklist::getType, 0).andEq(UserFriendAndBlacklist::getIsDeleted, false).select();
            List<User> userList = userDao.searchFriendOrGroup(parameter);
            ArrayList<User> users = new ArrayList<>();
            for (User user : userList) {
                if (user.getId().equals(userId)) {
                    continue; //搜索好友时不用搜索出自己来，也不需要加自己为好友
                }

                for (UserFriendAndBlacklist andBlacklist : select) {
                    if (user.getId().equals(andBlacklist.getRelevanceId())) {
                        users.add(user);
                        continue;
                    }
                }
            }
            userList.removeAll(users);
            return GlobalReponse.success(userList);
        }
        if (type == 1) {
            List<GroupChat> groupChats = groupChatDao.searchFriendOrGroup(parameter);
            ArrayList<GroupChat> chats = new ArrayList<>();
            for (GroupChat groupChat : groupChats) {
                GroupMembers single = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupChat.getId()).andEq(GroupMembers::getUserId, userId).andEq(GroupMembers::getIsDeleted, false).single();
                if (single == null) {
                    if (groupChat.getHead() == null || groupChat.getHead().equals("")) {
                        String head = "";
                        List<GroupMembers> groupMembers = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupChat.getId()).andEq(GroupMembers::getIsDeleted, 0).desc(GroupMembers::getType).limit(1, 9).select();
                        for (GroupMembers groupMember : groupMembers) {
                            User user = userDao.unique(groupMember.getUserId());
                            if (user.getHeadImage() != null) {
                                if (head.equals("")) {
                                    head = user.getHeadImage();
                                } else {
                                    head = head + "," + user.getHeadImage();
                                }
                            }
                        }
                        groupChat.setHead(head);
                    } else {
                        groupChat.setHead(groupChat.getHead());
                    }
                    chats.add(groupChat);
                }
            }
            //groupChats.removeAll(chats);
            return GlobalReponse.success(chats);
        }
        return GlobalReponse.fail("查询失败");
    }

    /**
     * 添加好友或申请加群 type 0好友 1群聊
     *
     * @param userId
     * @param id
     * @param type
     * @return
     */
    @Override
    public GlobalReponse addFriendOrGroup(Long userId, Long id, String remark, Integer type) {
        ApplyFor applyFor = new ApplyFor();
        if (type == 0) {
            ApplyFor single = applyForDao.createLambdaQuery().andEq(ApplyFor::getApplyId, userId).andEq(ApplyFor::getRelevanceId, id).andEq(ApplyFor::getIsDeleted, false).andEq(ApplyFor::getStatus, 0).andEq(ApplyFor::getType, 0).single();
            if (single != null) {
                single.setIsDeleted(true);
                single.setUpdateTime(new Date());
                single.setUpdateBy(userId.toString());
                applyForDao.updateTemplateById(single);
            }
            applyFor.setApplyId(userId);
            applyFor.setRelevanceId(id);
            if (remark != null && !remark.equals("")) {
                applyFor.setApplyRemark(remark);
            }
            applyFor.setCreateBy(userId.toString());
            applyFor.setCreateTime(new Date());
            applyFor.setType(0);
            applyFor.setStatus(0);
            applyFor.setIsDeleted(false);
            applyForDao.insertTemplate(applyFor, true);
            Boolean flag = tencentUtil.friendAdd(applyFor);
            if (flag) {
                return GlobalReponse.success("提交成功，请等待验证");
            } else {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return GlobalReponse.fail("提交失败");
            }
        }
        if (type == 1) {
            GroupChat groupChat = groupChatDao.unique(id);
            if (groupChat.getAddWay().equals(0)) {
                return GlobalReponse.fail("该群禁止申请加入");
            }
            //2不需要审核
            if (groupChat.getAddWay().equals(2)) {
                List<CreateGroupReturn> returns = tencentUtil.addGroupMember(id, userId.toString(), 0);
                for (CreateGroupReturn aReturn : returns) {
                    if (aReturn.getResult().equals("1")) {
                        User unique = userDao.unique(Long.valueOf(aReturn.getMember_Account()));
                        GroupMembers groupMembers = new GroupMembers();
                        groupMembers.setUserId(unique.getId());
                        groupMembers.setNickName(unique.getName());
                        groupMembers.setGroupChatId(groupChat.getId());
                        groupMembers.setCreateTime(new Date());
                        groupMembers.setCreateBy(userId.toString());
                        groupMembers.setType(0);
                        groupMembers.setIsDeleted(false);
                        groupMembersDao.insertTemplate(groupMembers);
                        UserFriendAndBlacklist groupFriend = new UserFriendAndBlacklist();
                        groupFriend.setUserId(unique.getId());
                        groupFriend.setRelevanceId(groupChat.getId());
                        groupFriend.setCreateTime(new Date());
                        groupFriend.setCreateBy(userId.toString());
                        groupFriend.setType(1);
                        groupFriend.setIsDeleted(false);
                        userFriendAndBlacklistDao.insertTemplate(groupFriend);
                    }
                }

                return GlobalReponse.success("提交成功，请等待验证");
            }
            ApplyFor single = applyForDao.createLambdaQuery().andEq(ApplyFor::getApplyId, userId).andEq(ApplyFor::getRelevanceId, id).andEq(ApplyFor::getIsDeleted, false).andEq(ApplyFor::getStatus, 0).andEq(ApplyFor::getType, 1).single();
            if (single != null) {
                single.setIsDeleted(true);
                single.setUpdateTime(new Date());
                single.setUpdateBy(userId.toString());
                applyForDao.updateTemplateById(single);
            }
            applyFor.setApplyId(userId);
            applyFor.setRelevanceId(id);
            applyFor.setApplyRemark(remark);
            applyFor.setCreateBy(userId.toString());
            applyFor.setCreateTime(new Date());
            applyFor.setType(1);
            applyFor.setStatus(0);
            applyFor.setIsDeleted(false);
            applyForDao.insertTemplate(applyFor);

            InviteAddGroup inviteAddGroup = inviteAddGroupDao.createLambdaQuery().andEq(InviteAddGroup::getGroupId, id).andEq(InviteAddGroup::getInviteeId, userId).andEq(InviteAddGroup::getStatus, 0).andEq(InviteAddGroup::getIsDeleted, 0).single();
            if (inviteAddGroup != null) {
                inviteAddGroup.setStatus(1);
                inviteAddGroup.setUpdateTime(new Date());
                inviteAddGroupDao.updateTemplateById(inviteAddGroup);
            }
            return GlobalReponse.success("提交成功，请等待验证");
        }
        return GlobalReponse.fail("提交失败");
    }

    /**
     * 创建群聊
     *
     * @return
     */
    @Override
    public GlobalReponse createGroup(Long userId, String ids) {
        if (ids.equals("")) {
            return GlobalReponse.fail("请选择人员后创建");
        }
        User user = userDao.unique(userId);
        GroupChat groupChat = new GroupChat();
        groupChat.setGroupNum(UUIDUtil.nineRandom());
        groupChat.setName(user.getName() + "创建的群聊");
        groupChat.setCreateTime(new Date());
        groupChat.setCreateBy(userId.toString());
        groupChat.setIsDeleted(false);
        groupChat.setAddWay(1);
        groupChat.setGroupType(0);
        groupChat.setHead(user.getHeadImage());
        groupChatDao.insertTemplate(groupChat, true);
        GroupMembers groupMembers1 = new GroupMembers();
        groupMembers1.setNickName(user.getName());
        groupMembers1.setUserId(userId);
        groupMembers1.setGroupChatId(groupChat.getId());
        groupMembers1.setCreateTime(new Date());
        groupMembers1.setCreateBy(userId.toString());
        groupMembers1.setType(2);
        groupMembers1.setIsDeleted(false);
        groupMembersDao.insertTemplate(groupMembers1);
        Boolean creategroup = tencentUtil.creategroup(groupChat);
        if (!creategroup) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return GlobalReponse.fail("创建失败");
        } else {
            groupChat.setTencentId(groupChat.getId().toString());
            groupChatDao.updateTemplateById(groupChat);
            UserFriendAndBlacklist groupMy = new UserFriendAndBlacklist();
            groupMy.setUserId(user.getId());
            groupMy.setRelevanceId(groupChat.getId());
            groupMy.setCreateTime(new Date());
            groupMy.setCreateBy(user.getId().toString());
            groupMy.setType(1);
            groupMy.setIsDeleted(false);
            userFriendAndBlacklistDao.insertTemplate(groupMy);
            List<CreateGroupReturn> list = tencentUtil.addGroupMember(groupChat.getId(), ids, 0);
            if (list.isEmpty()) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return GlobalReponse.fail("创建失败");
            }
            for (CreateGroupReturn aReturn : list) {
                if (aReturn.getResult().equals("1")) {
                    User unique = userDao.unique(Long.valueOf(aReturn.getMember_Account()));
                    GroupMembers groupMembers = new GroupMembers();
                    groupMembers.setUserId(unique.getId());
                    groupMembers.setNickName(unique.getName());
                    groupMembers.setGroupChatId(groupChat.getId());
                    groupMembers.setCreateTime(new Date());
                    groupMembers.setCreateBy(userId.toString());
                    groupMembers.setType(0);
                    groupMembers.setIsDeleted(false);
                    groupMembersDao.insertTemplate(groupMembers);
                    UserFriendAndBlacklist groupFriend = new UserFriendAndBlacklist();
                    groupFriend.setUserId(unique.getId());
                    groupFriend.setRelevanceId(groupChat.getId());
                    groupFriend.setCreateTime(new Date());
                    groupFriend.setCreateBy(user.getId().toString());
                    groupFriend.setType(1);
                    groupFriend.setIsDeleted(false);
                    userFriendAndBlacklistDao.insertTemplate(groupFriend);
                }
            }
        }
        return GlobalReponse.success("创建成功");
    }

    /**
     * 查看群详情
     *
     * @param userId
     * @param groupId
     * @return
     */
    @Override
    public GlobalReponse<GroupChatDetailVo> getGroupChatDetail(Long userId, Long groupId) {
        GroupChat groupChat = groupChatDao.unique(groupId);
        GroupChatDetailVo detailVo = new GroupChatDetailVo();
        BeanUtils.copyProperties(groupChat, detailVo);
        GroupMembers single = null;
        if (groupChat.getUpdateBy() == null) {
            single = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getUserId, groupChat.getCreateBy()).andEq(GroupMembers::getIsDeleted, false).single();
            User unique = userDao.unique(single.getUserId());
            if (single.getNickName() != null) {
                detailVo.setUpdateUsername(single.getNickName());
            } else {
                detailVo.setUpdateUsername(unique.getName());
            }
            detailVo.setUpdateHead(unique.getHeadImage());
        } else {
            single = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getUserId, groupChat.getUpdateBy()).andEq(GroupMembers::getIsDeleted, false).single();
            User unique = userDao.unique(single.getUserId());
            if (single.getNickName() != null) {
                detailVo.setUpdateUsername(single.getNickName());
            } else {
                detailVo.setUpdateUsername(unique.getName());
            }
            detailVo.setUpdateHead(unique.getHeadImage());
        }
        GroupMembers My = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getUserId, userId).andEq(GroupMembers::getIsDeleted, false).single();
        if (My != null) {
            detailVo.setNickName(My.getNickName());
            detailVo.setMyType(My.getType());
        }
        List<GroupMembers> members = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getIsDeleted, false).desc(GroupMembers::getNickName).desc(GroupMembers::getType).select();
        ArrayList<UserRelevanceVo> vos = new ArrayList<>();
        if (!members.isEmpty()) {
            for (GroupMembers member : members) {
                User user = userDao.unique(member.getUserId());
                UserRelevanceVo vo = new UserRelevanceVo();
                vo.setRelevanceId(user.getId());
                vo.setRelevanceImage(user.getHeadImage());
                if (member.getNickName() != null) {
                    vo.setRelevanceNickName(member.getNickName());
                } else {
                    vo.setRelevanceNickName(user.getName());
                }
                vos.add(vo);
            }
        }
        detailVo.setGroupMembers(vos);
        return GlobalReponse.success(detailVo);
    }

    /**
     * 修改昵称
     *
     * @param userId
     * @param groupId
     * @param nickName
     * @return
     */
    @Override
    public GlobalReponse updateNickName(Long userId, Long groupId, String nickName) {
        GroupMembers groupMembers = new GroupMembers();
        groupMembers.setUserId(userId);
        groupMembers.setGroupChatId(groupId);
        groupMembers.setIsDeleted(false);
        GroupMembers one = groupMembersDao.templateOne(groupMembers);
        one.setNickName(nickName);
        one.setUpdateBy(userId.toString());
        one.setUpdateTime(new Date());
        groupMembersDao.updateTemplateById(one);
        Boolean flag = tencentUtil.modifyGroupMemberInfo(one);
        if (!flag) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return GlobalReponse.success("修改失败");
        }
        return GlobalReponse.success("修改成功");
    }

    /**
     * 编辑群资料
     *
     * @param userId
     * @param groupDataDto
     * @return
     */
    @Override
    public GlobalReponse updateGroupData(Long userId, Long groupId, GroupDataDto groupDataDto) {
        GroupChat groupChat = groupChatDao.unique(groupId);
        if (!BeanIsNotEmpty.isNotEmptyBean(groupDataDto)) {
            GroupDataDto dataDto = new GroupDataDto();
            BeanUtils.copyProperties(groupChat, dataDto);
            return GlobalReponse.success(dataDto);
        }
        Boolean flag = null;

        if (groupChat.getHead() != null) {
            if (groupDataDto.getHead() != null) {
                if (groupChat.getName().equals(groupDataDto.getName()) && groupChat.getHead().equals(groupDataDto.getHead())) {
                    BeanUtils.copyProperties(groupDataDto, groupChat);
                    groupChat.setUpdateBy(userId.toString());
                    groupChat.setUpdateTime(new Date());
                    groupChatDao.updateTemplateById(groupChat);
                    return GlobalReponse.success("编辑成功");
                } else if (groupChat.getName().equals(groupDataDto.getName()) && !groupChat.getHead().equals(groupDataDto.getHead())) {
                    flag = tencentUtil.updateGroupName(groupChat.getId(), null, groupChat.getHead());
                } else if (!groupChat.getName().equals(groupDataDto.getName()) && groupChat.getHead().equals(groupDataDto.getHead())) {
                    flag = tencentUtil.updateGroupName(groupChat.getId(), groupDataDto.getName(), null);
                } else if (!groupChat.getName().equals(groupDataDto.getName()) && !groupChat.getHead().equals(groupDataDto.getHead())) {
                    flag = tencentUtil.updateGroupName(groupChat.getId(), groupDataDto.getName(), groupChat.getHead());
                }
            }
        } else {
            if (groupDataDto.getHead() != null) {
                if (groupChat.getName().equals(groupDataDto.getName())) {
                    flag = tencentUtil.updateGroupName(groupChat.getId(), null, groupChat.getHead());
                } else if (!groupChat.getName().equals(groupDataDto.getName())) {
                    flag = tencentUtil.updateGroupName(groupChat.getId(), groupDataDto.getName(), groupChat.getHead());
                }
            } else {
                if (groupChat.getName().equals(groupDataDto.getName())) {
                    BeanUtils.copyProperties(groupDataDto, groupChat);
                    groupChat.setUpdateBy(userId.toString());
                    groupChat.setUpdateTime(new Date());
                    groupChatDao.updateTemplateById(groupChat);
                    return GlobalReponse.success("编辑成功");
                } else if (!groupChat.getName().equals(groupDataDto.getName())) {
                    flag = tencentUtil.updateGroupName(groupChat.getId(), groupDataDto.getName(), null);
                }
            }
        }


        if (flag) {
            BeanUtils.copyProperties(groupDataDto, groupChat);
            groupChat.setUpdateBy(userId.toString());
            groupChat.setUpdateTime(new Date());
            groupChatDao.updateTemplateById(groupChat);
            return GlobalReponse.success("编辑成功");
        }
        return GlobalReponse.fail("编辑失败");
    }

    /**
     * 获取群成员列表
     *
     * @param groupId
     * @return
     */
    @Override
    public GlobalReponse getAllGroupMembers(Long userId, Long groupId, String keyword) {
        //List<GroupMembers> members = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getIsDeleted, false).desc(GroupMembers::getNickName).desc(GroupMembers::getType).select();
        if (keyword != null && keyword.equals("")) {
            keyword = null;
        }
        List<GroupMembers> members = groupMembersDao.getAllGroupMembers(groupId, keyword);
        ArrayList<UserRelevanceVo> vos = new ArrayList<>();
        ArrayList<UserRelevanceVo> groupVoS = new ArrayList<>();
        ArrayList<UserRelevanceVo> ownerList = new ArrayList<>();
        if (!members.isEmpty()) {
            for (GroupMembers member : members) {
                if (member.getType() == 2) {
                    UserRelevanceVo owner = new UserRelevanceVo();
                    User user = userDao.unique(member.getUserId());
                    owner.setAccount(user.getAccount());
                    owner.setRelevanceId(user.getId());
                    owner.setRelevanceImage(user.getHeadImage());
                    owner.setType(2);
                    if (member.getNickName() != null) {
                        owner.setRelevanceNickName(member.getNickName());
                    } else {
                        owner.setRelevanceNickName(user.getName());
                    }
                    //判断是否好友
                    UserFriendAndBlacklist friend = userFriendAndBlacklistDao.isFriend(userId, user.getId());
                    UserFriendAndBlacklist friend1 = userFriendAndBlacklistDao.isFriend1(userId, user.getId());
                    if (friend != null || friend1 != null) {
                        owner.setIsFriend(true);
                    } else {
                        owner.setIsFriend(false);
                    }
                    ownerList.add(owner);
                }
                if (member.getType() == 1) {
                    User user = userDao.unique(member.getUserId());
                    UserRelevanceVo vo = new UserRelevanceVo();
                    vo.setAccount(user.getAccount());
                    vo.setRelevanceId(user.getId());
                    vo.setType(1);
                    vo.setRelevanceImage(user.getHeadImage());
                    if (member.getNickName() != null) {
                        vo.setRelevanceNickName(member.getNickName());
                    } else {
                        vo.setRelevanceNickName(user.getName());
                    }
                    //判断是否好友
                    UserFriendAndBlacklist friend = userFriendAndBlacklistDao.isFriend(userId, user.getId());
                    UserFriendAndBlacklist friend1 = userFriendAndBlacklistDao.isFriend1(userId, user.getId());
                    if (friend != null || friend1 != null) {
                        vo.setIsFriend(true);
                    } else {
                        vo.setIsFriend(false);
                    }
                    vos.add(vo);
                }
                if (member.getType() == 0) {
                    User user = userDao.unique(member.getUserId());
                    UserRelevanceVo vo = new UserRelevanceVo();
                    vo.setAccount(user.getAccount());
                    vo.setRelevanceId(user.getId());
                    vo.setRelevanceImage(user.getHeadImage());
                    vo.setType(0);
                    if (member.getNickName() != null) {
                        vo.setRelevanceNickName(member.getNickName());
                    } else {
                        vo.setRelevanceNickName(user.getName());
                    }
                    //判断是否好友
                    UserFriendAndBlacklist friend = userFriendAndBlacklistDao.isFriend(userId, user.getId());
                    UserFriendAndBlacklist friend1 = userFriendAndBlacklistDao.isFriend1(userId, user.getId());
                    if (friend != null || friend1 != null) {
                        vo.setIsFriend(true);
                    } else {
                        vo.setIsFriend(false);
                    }
                    groupVoS.add(vo);
                }
            }
        }
        return GlobalReponse.success().setData1(ownerList).setData2(vos).setData3(groupVoS);
    }

    /**
     * 批量删除群成员
     *
     * @param userId
     * @param
     * @return
     */
    @Override
    public GlobalReponse deletedGroupMembers(Long userId, Long groupId, String ids) {
        String[] splitids = ids.split(",");
        Long[] idArr = (Long[]) ConvertUtils.convert(splitids, Long.class);
        Boolean flag = tencentUtil.deleteGroupMember(groupId, ids);
        if (flag) {
            for (Long id : idArr) {
                GroupMembers groupMembers = new GroupMembers();
                groupMembers.setUserId(id);
                groupMembers.setGroupChatId(groupId);
                groupMembers.setIsDeleted(false);
                GroupMembers templateOne = groupMembersDao.templateOne(groupMembers);
                templateOne.setIsDeleted(true);
                templateOne.setUpdateBy(userId.toString());
                templateOne.setUpdateTime(new Date());
                groupMembersDao.updateTemplateById(templateOne);

                KickOut kickOut = new KickOut();
                kickOut.setIsRead(0);
                kickOut.setUserId(id);
                kickOut.setRelevanceId(groupId);
                kickOut.setType(1);
                kickOut.setCreateBy(userId.toString());
                kickOut.setCreateTime(new Date());
                kickOut.setIsDeleted(false);
                kickOutDao.insertTemplate(kickOut);

                UserFriendAndBlacklist andBlacklist = new UserFriendAndBlacklist();
                andBlacklist.setType(1);
                andBlacklist.setUserId(id);
                andBlacklist.setRelevanceId(groupId);
                UserFriendAndBlacklist blacklist = userFriendAndBlacklistDao.templateOne(andBlacklist);
                blacklist.setIsDeleted(true);
                blacklist.setUpdateBy(userId.toString());
                blacklist.setUpdateTime(new Date());
                userFriendAndBlacklistDao.updateTemplateById(blacklist);

            }
            return GlobalReponse.success("删除成功");
        }
        return GlobalReponse.fail("删除失败");
    }

    /**
     * 获取未加入群的好友列表
     *
     * @param userId
     * @param groupId
     * @return
     */
    @Override
    public GlobalReponse<ArrayList<User>> getFriendList(Long userId, Long groupId, String keyword) {
        if (keyword != null && keyword.equals("")) {
            keyword = null;
        }
        List<GroupMembers> groupMembers = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andNotEq(GroupMembers::getUserId, userId).andEq(GroupMembers::getIsDeleted, false).select();
        //List<UserFriendAndBlacklist> friendList = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, userId).andEq(UserFriendAndBlacklist::getType, 0).andEq(UserFriendAndBlacklist::getIsDeleted, false).select();
        List<UserFriendAndBlacklist> friendList = userFriendAndBlacklistDao.getFriendList(userId, keyword);
        List<Long> memberIds = groupMembers.stream().map(GroupMembers::getUserId).collect(Collectors.toList());
        List<Long> friendIds = friendList.stream().map(UserFriendAndBlacklist::getRelevanceId).collect(Collectors.toList());
        friendIds.removeAll(memberIds);
        ArrayList<User> users = new ArrayList<>();
        for (Long friendId : friendIds) {
            User user = userDao.unique(friendId);
            users.add(user);
        }
        return GlobalReponse.success(users);
    }

    /**
     * 批量邀请成员/邀请好友加入群聊
     *
     * @param userId
     * @param groupId
     * @param idArr
     * @return
     */
    @Override
    public GlobalReponse addGroupMembers(Long userId, Long groupId, Long[] idArr) {
        // 先判断是不是群主邀请的，如果群主邀请直接进去
        String role = tencentUtil.getRoleInGroup(groupId, userId);
        boolean lean = false;
        if("Owner".equals(role)){
            lean = true;
        }
        GroupChat groupChat = groupChatDao.unique(groupId);
        for (Long aLong : idArr) {
            if (groupChat.getAddWay().equals(0)) {
                return GlobalReponse.fail("该群禁止申请加入");
            } else if (groupChat.getAddWay().equals(2) || lean) {
                System.out.println("*****执行直接加入**********：" + lean);
                List<CreateGroupReturn> returns = tencentUtil.addGroupMember(groupId, aLong.toString(), 1);
                for (CreateGroupReturn aReturn : returns) {
                    if (aReturn.getResult().equals("1")) {
                        User unique = userDao.unique(Long.valueOf(aReturn.getMember_Account()));
                        GroupMembers groupMembers = new GroupMembers();
                        groupMembers.setUserId(unique.getId());
                        groupMembers.setNickName(unique.getName());
                        groupMembers.setGroupChatId(groupChat.getId());
                        groupMembers.setCreateTime(new Date());
                        groupMembers.setCreateBy(userId.toString());
                        groupMembers.setType(0);
                        groupMembers.setIsDeleted(false);
                        groupMembersDao.insertTemplate(groupMembers);
                        UserFriendAndBlacklist groupFriend = new UserFriendAndBlacklist();
                        groupFriend.setUserId(unique.getId());
                        groupFriend.setRelevanceId(groupChat.getId());
                        groupFriend.setCreateTime(new Date());
                        groupFriend.setCreateBy(userId.toString());
                        groupFriend.setType(1);
                        groupFriend.setIsDeleted(false);
                        userFriendAndBlacklistDao.insertTemplate(groupFriend);
                    }
                }
            } else {
                System.out.println("*****执行审核加入**********：" + lean);
                InviteAddGroup inviteAddGroup = new InviteAddGroup();
                inviteAddGroup.setGroupId(groupId);
                inviteAddGroup.setInviterId(userId);
                inviteAddGroup.setInviteeId(aLong);
                inviteAddGroup.setStatus(1);
                inviteAddGroup.setIsDeleted(false);
                inviteAddGroup.setCreateBy(userId.toString());
                inviteAddGroup.setCreateTime(new Date());
                inviteAddGroupDao.insertTemplate(inviteAddGroup);
                // 直接到管理员这一步
                this.addFriendOrGroup(aLong, groupChat.getId(), null, 1);

            }
        }
        return GlobalReponse.success("邀请成功");
    }

    /**
     * 设置群管理员
     *
     * @param userId
     * @param groupId
     * @param addIds
     * @param deletedIds
     * @return
     */
    @Override
    public GlobalReponse setGroupAdministrator(Long userId, Long groupId, String addIds, String deletedIds) {
        String[] aSplitids = addIds.split(",");
        Long[] addArr = (Long[]) ConvertUtils.convert(aSplitids, Long.class);
        String[] dSplitids = deletedIds.split(",");
        Long[] deletedArr = (Long[]) ConvertUtils.convert(dSplitids, Long.class);
        if (!addIds.equals("")) {
            for (Long addId : addArr) {
                GroupChat groupChat = groupChatDao.unique(groupId);
                if (groupChat.getGroupType().equals(1)) {
                    User user = userDao.unique(addId);
                    if (user.getUserType().equals(1)) {
                        return GlobalReponse.fail("学生无法设置为管理员");
                    }
                }
                Boolean flag = tencentUtil.setGroupMember(addId, groupId, 1);
                if (flag) {
                    GroupMembers groupMembers = new GroupMembers();
                    groupMembers.setUserId(addId);
                    groupMembers.setGroupChatId(groupId);
                    groupMembers.setIsDeleted(false);
                    GroupMembers templateOne = groupMembersDao.templateOne(groupMembers);
                    templateOne.setType(1);
                    templateOne.setUpdateBy(userId.toString());
                    templateOne.setUpdateTime(new Date());
                    groupMembersDao.updateTemplateById(templateOne);
                }
            }
        }
        if (!deletedIds.equals("")) {
            for (Long deletedId : deletedArr) {
                Boolean flag = tencentUtil.setGroupMember(deletedId, groupId, 0);
                if (flag) {
                    GroupMembers groupMembers = new GroupMembers();
                    groupMembers.setUserId(deletedId);
                    groupMembers.setGroupChatId(groupId);
                    groupMembers.setIsDeleted(false);
                    GroupMembers templateOne = groupMembersDao.templateOne(groupMembers);
                    templateOne.setType(0);
                    templateOne.setUpdateBy(userId.toString());
                    templateOne.setUpdateTime(new Date());
                    groupMembersDao.updateTemplateById(templateOne);
                }
            }
        }
        return GlobalReponse.success("设置成功");
    }

    /**
     * 设置加群方式
     *
     * @param userId
     * @param groupId
     * @param type
     * @return
     */
    @Override
    public GlobalReponse updateAddGroupWay(Long userId, Long groupId, Integer type) {
        Boolean flag = tencentUtil.updateAddGroupWay(groupId, type);
        if (flag) {
            GroupChat groupChat = groupChatDao.unique(groupId);
            groupChat.setAddWay(type);
            groupChat.setUpdateBy(userId.toString());
            groupChat.setUpdateTime(new Date());
            groupChatDao.updateTemplateById(groupChat);
            return GlobalReponse.success("修改成功");
        }
        return GlobalReponse.fail("修改失败");
    }

    /**
     * 转让群
     *
     * @param userId
     * @param groupId
     * @param memberId
     * @return
     */
    @Override
    public GlobalReponse transferGroup(Long userId, Long groupId, Long memberId) {
        GroupMembers single = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getUserId, memberId).andEq(GroupMembers::getIsDeleted, false).single();
        if (single.getType().equals(0)) {
            return GlobalReponse.fail("只能转让群主给管理员");
        }
        Boolean flag = tencentUtil.changeGroupOwner(groupId, memberId);
        if (flag) {
            GroupChat groupChat = groupChatDao.unique(groupId);
            groupChat.setCreateBy(memberId.toString());
            groupChatDao.updateTemplateById(groupChat);

            single.setType(2);
            single.setUpdateBy(userId.toString());
            single.setUpdateTime(new Date());
            groupMembersDao.updateTemplateById(single);

            GroupMembers members = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupChat.getId()).andEq(GroupMembers::getUserId, userId).andEq(GroupMembers::getIsDeleted, false).single();
            members.setType(0);
            members.setUpdateBy(userId.toString());
            members.setUpdateTime(new Date());
            groupMembersDao.updateTemplateById(members);

            if (groupChat.getGroupType().equals(1)) {
                ClassAnd classAnd = classAndDao.unique(groupChat.getClassId());
                classAnd.setCreateBy(memberId.toString());
                classAndDao.updateTemplateById(classAnd);
                ClassMembers toMember = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classAnd.getId()).andEq(ClassMembers::getUserId, userId).andEq(ClassMembers::getIsDeleted, false).single();
                toMember.setType(2);
                classMembersDao.updateTemplateById(toMember);
                ClassMembers toCreate = classMembersDao.createLambdaQuery().andEq(ClassMembers::getClassId, classAnd.getId()).andEq(ClassMembers::getUserId, memberId).andEq(ClassMembers::getIsDeleted, false).single();
                toCreate.setType(3);
                classMembersDao.updateTemplateById(toCreate);
            }
            return GlobalReponse.success("转让成功");
        }
        return GlobalReponse.fail("转让失败");
    }

    /**
     * 解散群
     *
     * @param userId
     * @param groupId
     * @return
     */
    @Override
    public GlobalReponse dissolveGroup(Long userId, Long groupId) {
        GroupChat groupChat = groupChatDao.unique(groupId);
        if (groupChat.getGroupType().equals(1)) {
            return GlobalReponse.fail("班级群无法解散");
        }
        Boolean flag = tencentUtil.destroyGroup(groupId);
        if (flag) {
            groupChat.setIsDeleted(true);
            groupChat.setUpdateTime(new Date());
            groupChatDao.updateTemplateById(groupChat);
            List<GroupMembers> members = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getIsDeleted, false).select();
            for (GroupMembers member : members) {
                member.setIsDeleted(true);
                member.setUpdateTime(new Date());
                member.setUpdateBy(userId.toString());
                groupMembersDao.updateTemplateById(member);
            }
            List<UserFriendAndBlacklist> select = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getType, 1).andEq(UserFriendAndBlacklist::getRelevanceId, groupId).andEq(UserFriendAndBlacklist::getIsDeleted, false).select();
            for (UserFriendAndBlacklist andBlacklist : select) {
                andBlacklist.setIsDeleted(true);
                andBlacklist.setUpdateTime(new Date());
                andBlacklist.setUpdateBy(userId.toString());
                userFriendAndBlacklistDao.updateTemplateById(andBlacklist);
            }
            return GlobalReponse.success("解散成功");
        }
        return GlobalReponse.fail("解散失败");
    }

    /**
     * 退出群聊
     *
     * @param userId
     * @param groupId
     * @return
     */
    @Override
    public GlobalReponse quitGroup(Long userId, Long groupId) {
        Boolean flag = tencentUtil.deleteGroupMember(groupId, userId.toString());
        if (flag) {
            GroupMembers single = groupMembersDao.createLambdaQuery().andEq(GroupMembers::getGroupChatId, groupId).andEq(GroupMembers::getUserId, userId).andEq(GroupMembers::getIsDeleted, false).single();
            single.setIsDeleted(true);
            single.setUpdateTime(new Date());
            single.setUpdateBy(userId.toString());
            groupMembersDao.updateTemplateById(single);

            UserFriendAndBlacklist userFriendAndBlacklist = userFriendAndBlacklistDao.createLambdaQuery().andEq(UserFriendAndBlacklist::getUserId, userId).andEq(UserFriendAndBlacklist::getRelevanceId, groupId).andEq(UserFriendAndBlacklist::getType, 1).andEq(UserFriendAndBlacklist::getIsDeleted, false).single();
            if (userFriendAndBlacklist != null) {
                userFriendAndBlacklist.setIsDeleted(true);
                userFriendAndBlacklist.setUpdateTime(new Date());
                userFriendAndBlacklist.setUpdateBy(userId.toString());
                userFriendAndBlacklistDao.updateTemplateById(userFriendAndBlacklist);
            }
            return GlobalReponse.success("已退出");
        }
        return GlobalReponse.fail("退出失败");
    }
}
